package game.leon.engine.net;

import game.leon.engine.net.codec.GateCodecFactory;
import game.leon.engine.net.codec.GateRawMessage;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;

/**
 * User: bianpeng
 * Date: 11-12-27
 */
public class GameClient {
    private NioSocketConnector connector;
    private IoSession session;
    public void connect(String host, int port, GameMessageHandler messageHandler) {
        // initialize
        connector = new NioSocketConnector();
        connector.setConnectTimeoutMillis(1000);
        GateCodecFactory leonCodecFactory = new GateCodecFactory();
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.getFilterChain().addLast("protocol",
                new ProtocolCodecFilter(leonCodecFactory));
        connector.setHandler(new GameIoHandler(messageHandler));
        // start connect
        ConnectFuture connectFuture = connector.connect(new InetSocketAddress(host, port));
        connectFuture.awaitUninterruptibly();
        session = connectFuture.getSession();
    }
    public void send(GateRawMessage message) {
        session.write(message);
    }
}
